package com.lottery.service.qiuqiu.wealthService;

import com.lottery.dao.qiuqiu.accoutDao.CustomerServiceDao;
import com.lottery.dao.qiuqiu.accoutDao.UserDao;
import com.lottery.dao.qiuqiu.lobbyDao.BettinginfoDao;
import com.lottery.dao.qiuqiu.wealthDao.AccountDao;
import com.lottery.dao.qiuqiu.wealthDao.AccountTransactionDao;
import com.lottery.dto.PageDto;
import com.lottery.dto.RechrageDto;
import com.lottery.dto.ResultDto;
import com.lottery.entity.*;
import com.lottery.initData.InitData;
import com.lottery.service.qiuqiu.JedisClient;
import com.lottery.utils.DateUtil;
import com.lottery.utils.DealWithDouble;
import com.lottery.utils.RandCodeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class WealthService {
    @Resource
    private AccountTransactionDao accountTransactionDao;
    @Resource
    private UserDao userDao;
    @Resource
    private AccountDao accountDao;
    @Resource
    private CustomerServiceDao cusDao;
    @Resource
    private BettinginfoDao bettinginfoDao;


    @Resource
    private JedisClient jedis;

    DecimalFormat df = new DecimalFormat("#.##");


    public void SearchRechargeByUserId(Integer userId, Integer pageNow, Integer pageSize, Integer state, ResultDto result) throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<Integer> integers = new ArrayList<>();
        integers.add(1);
        params.put("transactionType", integers);
        List<RechrageDto> rechrageDtos = searchDetailUtils(userId, params, pageNow, pageSize, state);
        //判断是不是最后一页
        if (rechrageDtos.size() < pageSize) {
            result.setResultData(true, "查询数据成功,并且查询是最后条记录了", 2, rechrageDtos);
        } else {
            result.setResultData(true, "查询数据成功", 0, rechrageDtos);
        }
    }

    public void SearchRechargeById(Integer id, Integer userId, ResultDto result) throws Exception {
        RechrageDto rechrageDto = new RechrageDto();
        //查询用户信息
        User user = userDao.selectId(userId);
        rechrageDto.setUsername(user.getUserName());

        //查询用户的当前余额
        Account account = accountDao.selectAccountByUserId(userId);
        rechrageDto.setRemainder(Double.parseDouble(df.format(account.getAccountFunds())));

        //查询记录信息
        AccountTransaction accountTransaction = accountTransactionDao.selectAccountTransactionById(id);
        rechrageDto.setMoney(Double.parseDouble(df.format(accountTransaction.getTransactionMoney())));
        rechrageDto.setTime(DateUtil.getFormatDate(accountTransaction.getTransactionDate(), "yyyy-MM-dd HH:mm:ss"));
        rechrageDto.setFinishTime(accountTransaction.getFinishTime());
        rechrageDto.setState(accountTransaction.getState() + "");
        rechrageDto.setDataSource("正式数据");
        rechrageDto.setRemark(InitData.RECHARGE_CANAL.get(accountTransaction.getCashType()));

        //查询处理人员信息
        int cusId = accountTransaction.getOperator();
        if (cusId != 0) {
            CustomerServiceInformation customerServiceInformation = cusDao.selectById(cusId);
            rechrageDto.setOperator(customerServiceInformation.getNickName());
        }

        result.setData(rechrageDto);
        result.setResultData(true, "查询成功", 0, null);
    }


    public void searchWithdraw(Integer userId, Integer pageNow, Integer pageSize, Integer state, ResultDto result) throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<Integer> integers = new ArrayList<>();
        integers.add(2);
        params.put("transactionType", integers);
        List<RechrageDto> rechrageDtos = searchDetailUtils(userId, params, pageNow, pageSize, state);
        //判断是不是最后一页
        if (rechrageDtos.size() < pageSize) {
            result.setResultData(true, "查询数据成功,并且查询是最后条记录了", 2, rechrageDtos);
        } else {
            result.setResultData(true, "查询数据成功", 0, rechrageDtos);
        }
    }

    public void searchWithdrawById(Integer id, Integer userId, ResultDto result) {
        RechrageDto rechrageDto = new RechrageDto();
        //查询用户信息
        User user = userDao.selectId(userId);
        rechrageDto.setUsername(user.getUserName());

        //查询用户的当前余额
        Account account = accountDao.selectAccountByUserId(userId);
        rechrageDto.setRemainder(Double.parseDouble(df.format(account.getAccountFunds())));

        //查询记录信息
        AccountTransaction accountTransaction = accountTransactionDao.selectAccountTransactionById(id);
        rechrageDto.setMoney(Double.parseDouble(df.format(accountTransaction.getTransactionMoney())));
        rechrageDto.setTime(DateUtil.getFormatDate(accountTransaction.getTransactionDate(), "yyyy-MM-dd hh:mm:ss"));
        rechrageDto.setState(accountTransaction.getState() + "");
        rechrageDto.setDataSource("正式数据");

        result.setData(rechrageDto);
        result.setResultData(true, "查询成功", 0, null);
    }


    public void cancelWithdrawById(Integer id, ResultDto result) throws Exception {
        accountTransactionDao.cancelWithdrawById(id);
        result.setResultData(true, "取消下分成功", 0, null);
    }

    //查询通用方法

    private List<RechrageDto> searchDetailUtils(Integer userId, Map<String, Object> params, Integer pageNow, Integer pageSize, Integer state) {
        //查询用户的名字
        User user = userDao.selectId(userId);
        String username = user.getUserName();
        //查询上分记录
        Account account = accountDao.selectAccountByUserId(userId);
        int id = account.getId();
        params.put("accountId", id);
        params.put("skip", (pageNow - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("state", state);
        //将数据转码
        List<RechrageDto> rechrageDtos = new ArrayList<>();
        RechrageDto rechrageDto;
        List<AccountTransaction> list = accountTransactionDao.selectTranstionList(params);
        for (AccountTransaction ac : list) {
            rechrageDto = new RechrageDto();
            double get = Double.parseDouble(df.format(ac.getTransactionMoney()));
            rechrageDto.setId(ac.getId());
            rechrageDto.setMoney(get);
            rechrageDto.setState(ac.getState() + "");
            rechrageDto.setTime(DateUtil.getFormatDate(ac.getTransactionDate(), "yyyy-MM-dd hh:mm:ss"));
            rechrageDto.setDataSource("正式数据");
            rechrageDto.setUsername(username);
            rechrageDtos.add(rechrageDto);
        }

        return rechrageDtos;
    }

    public void searchWealthInfo(int userId, int loginType, Integer lotteyType, ResultDto result) throws Exception {
        String moneyFormat = "";
        if (loginType == 0) {
            //查询账户余点
            Account account = accountDao.selectAccountByUserId(userId);
            double money = account.getAccountFunds();
            moneyFormat = df.format(money);
        } else {
            moneyFormat = jedis.hget(userId + "::" + lotteyType, "amount");
        }

        //查询今天收益
        //测试完毕放开这个
        String formatDate = DateUtil.getFormatDate("YYYY-MM-dd");
        //String formatDate = "2018-05-05";
        double bet = bettinginfoDao.searchYesterdayBet(userId, formatDate);
        double win = bettinginfoDao.searchYesterdayWin(userId, formatDate);

        double nowProfit = DealWithDouble.sub(win, bet, 2, 4);

        //将数据封装返回
        Map<String, Object> map = new HashMap<>();
        map.put("yuDian", moneyFormat);
        map.put("nowProfit", nowProfit);
        result.setData(map);
        result.setResultData(true, "查询数据成功", 0, null);
    }

    public void rechargeByUserId(Integer userId, Integer money, ResultDto result) throws Exception {
        if (money >= 100) {
            User user = userDao.selectId(userId);
            AccountTransaction ac = new AccountTransaction();
            //根据userId查出accountId
            Account account = accountDao.selectAccountByUserId(userId);
            ac.setAccountId(account.getId());
            ac.setTransactionDate(new Date());
            ac.setTransactionMoney(money);
            ac.setOrderId(RandCodeUtil.getOrderId());
            ac.setTransactionType(1);
            ac.setMoneySources("上分");
            ac.setMoney(money);
            ac.setAgencyMark(Integer.parseInt(user.getAgencyId()));
            ac.setState(0);
            accountTransactionDao.insertAccountTransaction(ac);
            result.setResultData(true, "上分记录已提交", 0, null);
        } else {
            result.setResultData(false, "上分不能低于100", 2, null);
        }

    }

    public void withdrawByuserId(Integer userId, Integer money, String cashAccount, Integer cashType, ResultDto result) {
        Account account = accountDao.selectAccountByUserId(userId);
        double sub = DealWithDouble.sub(account.getAccountFunds(), money, 2, 4);
        if (money < 100) {
            result.setResultData(false, "下分不能小于100", 2, null);
        } else if (money > 5000 && cashType != 1) {
            result.setResultData(false, "下分金额大于5000只能走银行渠道", 3, null);
        } else if (cashAccount.length() == 0) {
            result.setResultData(false, "下分账号不能为空", 4, null);
        } else if (sub < 0) {
            result.setResultData(false, "您的下分金额不足", 5, null);
        }
        {
            User user = userDao.selectId(userId);
            AccountTransaction ac = new AccountTransaction();
            ac.setAccountId(account.getId());
            ac.setTransactionMoney(money);
            ac.setTransactionDate(new Date());
            ac.setMoney(money);
            ac.setOrderId(RandCodeUtil.getOrderId());
            ac.setCashAccout(cashAccount);
            ac.setCashType(cashType);
            ac.setMoneySources("下分");
            ac.setState(0);
            ac.setAgencyMark(Integer.parseInt(user.getAgencyId()));
            ac.setTransactionType(2);
            accountTransactionDao.insertAccountTransaction(ac);
            account.setAccountFunds(sub);
            accountDao.updateAccountMoneyById(account);
            result.setResultData(true, "下分申请提交成功", 0, null);
        }
    }


    //
    public void searchMypurse(Integer userId, String startTime, String endTime, ResultDto result) throws Exception {
        PageDto page = new PageDto();
        page.setPageNow(-1);
        Map<String, Object> params = new HashMap<>();
        Account account = accountDao.selectAccountByUserId(userId);
        params.put("accountId", account.getId());
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("page", page);
        List<AccountTransaction> list = accountTransactionDao.selectMypurseRecord(params);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (list.size() > 0) {
            list.forEach((k) -> {
                Map<String, Object> ccMap = new HashMap<>();
                int state = 0;
                switch (k.getTransactionType()){
                    case 1:
                        state=2;
                        break;
                    case 2:
                    case 6:
                        state = 3;
                        break;
                    case 3:
                        state = 0;
                        break;
                    case 4:
                        state = 1;
                        break;
                    case 7:
                        state = 4;
                        break;
                }
                ccMap.put("state", state);
                ccMap.put("changeMoney", k.getTransactionMoney());
                ccMap.put("accountMoney", k.getAccountFunds());
                ccMap.put("remark",k.getRemarks());
                ccMap.put("date", DateUtil.getFormatDate(k.getTransactionDate(),"MM.dd HH:mm:ss"));
                resultList.add(ccMap);
            });
//        //封装下注和中奖记录
//        List<Bettinginfo> bettinginfos = bettinginfoDao.searchAllbetRecordByUserID(params);
//        if (bettinginfos.size() > 0) {
//            for (Bettinginfo k : bettinginfos) {
//                if(k.getState() == 2){
//                    continue;
//                }
//                packageMyPurse(list, k);
//            }
//        }
//
//        //封装流水记录
//        packageWater(userId,list,params);
//        //封装上下分记录
//        packUpAndDown(userId,list,params);
//
//        if(list.size()>0){
//            list.sort(new Comparator<Map<String, Object>>() {
//                @Override
//                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
//                    long num1 =(long)o1.get("date");
//                    long num2 = (long)o2.get("date");
//                    if(num1>num2){
//                        return -1;
//                    }else if(num1<num2){
//                        return 1;
//                    }else{
//                        return 0;
//                    }
//                }
//            });
//            list.forEach((k)->{
//                k.put("date",DateUtil.stampToDate((long)k.get("date"),"MM.dd HH:mm:ss"));
//            });
            result.setData(page);
            result.setResultData(true, "获取信息成功", 0, resultList);
        } else {
            result.setResultData(false, "no data", 0, null);
        }

    }

    private void packUpAndDown(Integer userId, LinkedList<Map<String, Object>> list, Map<String, Object> accoutParams) {
        Account account = accountDao.selectAccountByUserId(userId);
        accoutParams.put("accountId", account.getId());
        accoutParams.put("transactionType", 1);
        //上分记录
        List<AccountTransaction> zzList = accountTransactionDao.selectInfoByAccountId(accoutParams);
        if (zzList.size() > 0) {
            for (AccountTransaction k : zzList) {
                Map<String, Object> ccMap = new HashMap<>();
                ccMap.put("state", 2);
                ccMap.put("changeMoney", k.getTransactionMoney());
                ccMap.put("accountMoney", k.getCashAccout());
                CustomerServiceInformation cus = cusDao.selectById(k.getOperator());
                String remark = "充值上分,审核人[" + cus.getNickName()
                        + "]";
                ccMap.put("remark", remark);
                ccMap.put("date", k.getTransactionDate().getTime());
                list.add(ccMap);
            }
        }
        //下分记录
        accoutParams.put("transactionType", 2);
        List<AccountTransaction> downList = accountTransactionDao.selectInfoByAccountId(accoutParams);
        if (zzList.size() > 0) {
            for (AccountTransaction k : zzList) {
                Map<String, Object> ccMap = new HashMap<>();
                ccMap.put("state", 3);
                ccMap.put("changeMoney", k.getTransactionMoney());
                ccMap.put("accountMoney", k.getCashAccout());
                CustomerServiceInformation cus = cusDao.selectById(k.getOperator());
                String remark = "会员申请下分";
                ccMap.put("remark", remark);
                ccMap.put("date", k.getTransactionDate().getTime());
                list.add(ccMap);
            }
        }


    }

    private void packageWater(Integer userId, LinkedList<Map<String, Object>> list, Map<String, Object> accoutParams) {
        Account account = accountDao.selectAccountByUserId(userId);
        accoutParams.put("accountId", account.getId());
        accoutParams.put("transactionType", 7);
        List<AccountTransaction> accountTransaction = accountTransactionDao.selectInfoByAccountId(accoutParams);
        if (accountTransaction.size() > 0) {
            accountTransaction.forEach((k) -> {
                Map<String, Object> aaMap = new HashMap<>();
                aaMap.put("state", 4);
                aaMap.put("changeMoney", k.getTransactionMoney());
                aaMap.put("accountMoney", k.getCashAccout());
                String remark = DateUtil.getFormatDate(k.getTransactionDate(), "MM.dd") + "流水" + k.getMoney()
                        + "返水1%";
                aaMap.put("remark", remark);
                aaMap.put("date", k.getTransactionDate().getTime());
                list.add(aaMap);
            });

        }
    }

    private void packageMyPurse(LinkedList<Map<String, Object>> list, Bettinginfo k) {
        Map<String, Object> map = new HashMap<>();
        map.put("state", k.getState());
        map.put("changeMoney", k.getAccountChange());
        map.put("accountMoney", k.getAccountMoney());
        String expect = "";
        if (k.getLotteyType() == 1) {
            expect = k.getExpect().substring(4);
        } else if (k.getLotteyType() == 3) {
            expect = k.getExpect();
        }
        String remark = "[" + k.getPlaywayName() + "]期号[" + expect + "]竞猜[" + k.getBettingrule() + "]";
        map.put("remark", remark);
        map.put("date", k.getBettingDate().getTime());
        list.add(map);
    }
}
